from flask import Blueprint, request

from applications.common.utils.response_data import response_success, response_page, response_fail
from applications.models.comment_model import Comment
from applications.models.comment_thump_model import CommentThumbs
from applications.models.post_collections_model import PostCollections
from applications.models.post_model import Post, db
from applications.models.user_model import User
from applications.models.voice_detail_model import VoiceDetail
from sqlalchemy import func
from sqlalchemy.exc import IntegrityError, SQLAlchemyError

bp = Blueprint('post', __name__, url_prefix='/post')


@bp.post('/pageNewPostList')
def get_new_posts():
    user_id = request.headers.get('uid')
    # 子查询：标记用户收藏的 post_id
    is_collected_subquery = db.session.query(
        PostCollections.post_id,
        func.count(PostCollections.post_id).label('is_collected')
    ).filter(PostCollections.uid == user_id).group_by(PostCollections.post_id).subquery()

    collection_count_subquery = (
        db.session.query(
            PostCollections.post_id,
            func.count(PostCollections.post_id).label('collection_count')
        ).group_by(PostCollections.post_id).subquery()
    )

    comment_count_subquery = (
        db.session.query(
            Comment.post_id,
            func.count(Comment.id).label('comment_count')
        ).group_by(Comment.post_id).subquery()
    )
    # 主查询：获取文章列表并标记是否收藏
    post_pageation = db.session.query(
        Post,
        User,
        VoiceDetail,
        func.coalesce(collection_count_subquery.c.collection_count, 0).label('collection_count'),
        func.coalesce(comment_count_subquery.c.comment_count, 0).label('comment_count'),
        func.coalesce(is_collected_subquery.c.is_collected, 0).label('is_collected')
    ).join(User, Post.uid == User.uid) \
        .outerjoin(VoiceDetail, Post.id == VoiceDetail.post_id) \
        .outerjoin(collection_count_subquery, Post.id == collection_count_subquery.c.post_id) \
        .outerjoin(comment_count_subquery, Post.id == comment_count_subquery.c.post_id) \
        .outerjoin(is_collected_subquery, Post.id == is_collected_subquery.c.post_id) \
        .group_by(Post.id, User.uid, VoiceDetail.id) \
        .order_by(Post.create_time.desc()) \
        .paginate_cus()
    total = post_pageation.total
    posts = post_pageation.items
    posts_list = []
    for post, user, voice_detail, collection_count, comment_count,is_collected in posts:
        post_data = post.to_dict()
        user_data = user.to_dict() if user else None
        voice_data = voice_detail.to_dict() if voice_detail else None
        post_data['userInfo'] = user_data
        post_data["voiceInfo"] = voice_data
        post_data["thumpCount"] = collection_count
        post_data["commentCount"] = comment_count
        post_data["isCollection"] = is_collected
        # TODO 后期返回
        post_data["tag"] = "美女"
        posts_list.append(post_data)
    return response_page(
        data=posts_list,
        total=total,
        page=post_pageation.page,
        per_page=post_pageation.per_page,
        total_pages=post_pageation.total_pages
    )


@bp.post('/addPostCollection')
def add_post_collections():
    try:
        data = request.get_json()
        post_id = data.get('post_id')
        user_id = data.get('uid')

        if not post_id or not user_id:
            return response_fail(code=400, msg="参数错误，点赞失败")

        # 添加到 PostCollections
        post_collection = PostCollections(post_id=post_id, uid=user_id)
        db.session.add(post_collection)
        db.session.commit()

        return response_success(msg="点赞成功")

    except IntegrityError:
        db.session.rollback()
        return response_fail(code=409, msg="不要重复点赞哦~")
    except Exception as e:
        db.session.rollback()
        return response_fail(code=e.code, msg=str(e))


@bp.get('/postDetail/<post_id>')
def get_post_detail(post_id):
    user_id = request.headers.get('uid')

    # 子查询：标记用户点赞的 post_id
    is_liked_subquery = db.session.query(
        PostCollections.post_id,
        func.count(PostCollections.post_id).label('is_liked')
    ).filter(PostCollections.uid == user_id).group_by(PostCollections.post_id).subquery()

    # 主查询：获取文章详情并标记是否点赞和点赞数量
    post_detail_query = db.session.query(
        Post,
        User,
        VoiceDetail,
        func.count(PostCollections.post_id).label('like_count'),
        func.coalesce(is_liked_subquery.c.is_liked, 0).label('is_liked')
    ).join(User, Post.uid == User.uid) \
        .outerjoin(VoiceDetail, Post.id == VoiceDetail.post_id) \
        .outerjoin(PostCollections, Post.id == PostCollections.post_id) \
        .outerjoin(is_liked_subquery, Post.id == is_liked_subquery.c.post_id) \
        .filter(Post.id == post_id) \
        .group_by(Post.id, User.uid, VoiceDetail.id, is_liked_subquery.c.is_liked) \
        .first()

    if post_detail_query:
        post, user, voice_detail, like_count, is_liked = post_detail_query
        post_data = post.to_dict()
        post_data["userInfo"] = user.to_dict() if user else None
        post_data["voiceInfo"] = voice_detail.to_dict() if voice_detail else None
        post_data["thumpCount"] = like_count
        post_data["isCollection"] = is_liked

        return response_success(data=post_data)
    else:
        return response_fail(msg="Post not found")


@bp.post('/pageCommentListByPostId/<post_id>')
def get_comment_list(post_id):
    user_id = request.headers.get('uid')
    is_collected_subquery = db.session.query(
        CommentThumbs.c_id,
        func.count(CommentThumbs.c_id).label('is_collected')
    ).filter(CommentThumbs.uid == user_id).group_by(CommentThumbs.c_id).subquery()

    comment_pageation = db.session.query(
        Comment,
        User,
        VoiceDetail,
        func.count(CommentThumbs.c_id).label('thumbs_count'),
        func.coalesce(is_collected_subquery.c.is_collected, 0).label('is_collected')
    ) \
        .filter(Comment.post_id == post_id, Comment.pid == 0) \
        .join(User, Comment.uid == User.uid) \
        .outerjoin(VoiceDetail, VoiceDetail.comment_id == Comment.id) \
        .outerjoin(CommentThumbs, CommentThumbs.c_id == Comment.id) \
        .outerjoin(is_collected_subquery, is_collected_subquery.c.c_id == Comment.id) \
        .group_by(Comment.id) \
        .order_by(Comment.create_time.desc()) \
        .paginate_cus()
    total = comment_pageation.total
    comments = comment_pageation.items
    comment_list = []

    # 计算最高的点赞数
    max_thumbs_count = 0
    for comment, user, voice_detail, thumbs_count, is_collected in comments:
        if thumbs_count > max_thumbs_count:
            max_thumbs_count = thumbs_count

    for comment, user, voice_detail, thumbs_count, is_collected in comments:
        comment_data = comment.to_dict()
        user_data = user.to_dict() if user else None
        voice_data = voice_detail.to_dict() if voice_detail else None
        comment_data['userInfo'] = user_data
        comment_data["voiceInfo"] = voice_data
        comment_data["thumpCount"] = thumbs_count
        comment_data["isCollection"] = is_collected
        comment_data["isHot"] = 1 if thumbs_count == max_thumbs_count else 0

        # 查询子评论及其用户信息
        children_comments = db.session.query(
            Comment,
            User
        ) \
            .filter(Comment.post_id == post_id) \
            .filter(Comment.pid == comment.id) \
            .join(User, Comment.uid == User.uid) \
            .order_by(Comment.create_time.asc()) \
            .all()

        children_data = []
        for child_comment, child_user in children_comments:
            child_comment_data = child_comment.to_dict()
            child_user_data = child_user.to_dict() if child_user else None
            child_comment_data['userInfo'] = child_user_data
            children_data.append(child_comment_data)

        comment_data['children'] = children_data
        comment_list.append(comment_data)

    return response_page(
        data=comment_list,
        total=total,
        page=comment_pageation.page,
        per_page=comment_pageation.per_page,
        total_pages=comment_pageation.total_pages
    )


@bp.post('/addCommentCollection')
def add_comment_collections():
    try:
        data = request.get_json()
        comment_id = data.get('comment_id')
        user_id = data.get('uid')

        if not comment_id or not user_id:
            return response_fail(code=400, msg="参数错误，点赞失败")

        # 添加到 PostCollections
        comment_collection = CommentThumbs(c_id=comment_id, uid=user_id)
        db.session.add(comment_collection)
        db.session.commit()

        return response_success(msg="点赞成功")

    except IntegrityError:
        db.session.rollback()
        return response_fail(code=409, msg="不要重复点赞哦~")
    except Exception as e:
        db.session.rollback()
        return response_fail(code=e.code, msg=str(e))


@bp.post('/repleyComment')
def add_repley_comment():
    try:
        user_id = request.headers.get('uid')
        data = request.get_json()
        content = data.get('content')
        pid = data.get('pid')
        postId = data.get('postId')
        comment = Comment(uid=user_id, content=content, pid=pid, post_id=postId)
        db.session.add(comment)
        db.session.commit()
        user = User.query.filter_by(uid=user_id).first()
        comment = comment.to_dict()
        comment['userInfo'] = user.to_dict()
        return response_success(
            data=comment
        )
    except Exception as e:
        db.session.rollback()
        error_code = getattr(e, 'code', 500)
        return response_fail(code=error_code, msg=str(e))


@bp.post('/createPost')
def create_post():
    uid = request.headers.get('uid')
    try:
        data = request.get_json()
        content = data.get('content')
        media = data.get('media')
        voice_url = data.get('voice_url')
        voice_length = data.get('voice_length')

        # 创建并添加 Post 对象
        post = Post(uid=uid, content=content, media=media)
        db.session.add(post)
        db.session.flush()  # 使post对象获取到post_id
        # 创建并添加 VoiceDetail 对象
        if voice_url:
            voice_detail = VoiceDetail(post_id=post.id, voice_url=voice_url, voice_length=voice_length)
            db.session.add(voice_detail)
        else:
            db.session.rollback()
            return response_fail(msg="请上传音频")
        db.session.commit()
        # post_data = post.to_dict()
        # post_data["voiceInfo"] = voice_detail.to_dict()
        return response_success(msg="创建成功")

    except SQLAlchemyError as e:
        db.session.rollback()
        return response_fail(code=e.code if hasattr(e, 'code') else 500, msg=str(e))

    except Exception as e:
        db.session.rollback()
        return response_fail(code=500, msg=str(e))
